package cn.virens.server.aio.channel.handler;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.CompletionHandler;

import cn.virens.server.aio.channel.AioChannelSimple;

public class AioChannelWriteHandler implements CompletionHandler<Integer, ByteBuffer> {
	private final AioChannelSimple channel;

	public AioChannelWriteHandler(AioChannelSimple channel) {
		this.channel = channel;
	}

	@Override
	public void completed(Integer result, ByteBuffer buffer) {
		channel.setLastWriteTick(System.currentTimeMillis());

		if (channel.getAioDataWriteListener() != null) {
			channel.getAioDataWriteListener().onWrite(channel, buffer, result);
		}
	}

	@Override
	public void failed(Throwable exc, ByteBuffer buffer) {
		if (exc instanceof AsynchronousCloseException) {
			channel.getAcceptHandler().unbindUid(channel);
		} else if (exc instanceof ClosedChannelException) {
			channel.getAcceptHandler().unbindUid(channel);
		} else if (channel.getAioDataErrorListener() != null) {
			channel.getAioDataErrorListener().onError(channel, buffer, exc);
		}
	}

}
